//
//  DetailViewController.m
//  一点互助
//
//  Created by rimi on 16/8/24.
//  Copyright © 2016年 zhangboqiu. All rights reserved.
//

#import "DetailViewController.h"
#import "UIViewController+NavagitionBar.h"
#import "ResponseManager.h"
#import "ConfigDefine.h"
#import "DetailHeaderView.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "DetailTableViewCell.h"
#import "DetailHeaderAnotherView.h"
#import "DetailAnotherTableViewCell.h"
#import "UserModel.h"
#import "PayViewController.h"
#import "MemberViewController.h"
#import "CommentView.h"
#import "UIViewController+NavagitionBar.h"

@interface DetailViewController ()<UITableViewDelegate,UITableViewDataSource,DetailHeaderAnotherViewDelegate,UIScrollViewDelegate,UITextViewDelegate,CommentViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) UIView *headerview;
@property (strong, nonatomic) NSMutableArray *dataSource;
@property (assign, nonatomic) CGRect cellHeight;
@property (strong, nonatomic) DetailHeaderAnotherView *anotherHeaderView;
@property (weak, nonatomic) IBOutlet UIButton *payBtn;
@property (assign, nonatomic) BOOL btnBool;
@property (strong, nonatomic) CommentView *commentView;
@property (strong, nonatomic) UIButton *btn;
@property (assign, nonatomic) NSInteger flag;
@end

@implementation DetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    PLLOG(@"WishID:%ld",self.model.wishId);
    if (self.model.isFavorites) {
        self.flag = 1;
    }else{
        self.flag = 0;
    }
    self.title = @"愿望详情";
    self.btnBool = YES;
    UINib *nib = [UINib nibWithNibName:@"DetailTableViewCell" bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:@"DetailTableViewCell"];
    UINib *nib2 = [UINib nibWithNibName:@"DetailAnotherTableViewCell" bundle:nil];
    [self.tableView registerNib:nib2 forCellReuseIdentifier:@"DetailAnotherTableViewCell"];
    [self setupBackItem];
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    [self addSubviews];
    [self getRequest];
}
-(void)addImageView:(UIScrollView *)scrollview{
    for (int i = 0; i < self.model.photoArray.count; i++) {
        NSString *photoStr = self.model.photoArray[i];
        UIImageView *imageview = [[UIImageView alloc]initWithFrame:CGRectMake(i * kScreenWidth, 0, kScreenWidth, scrollview.frame.size.height)];
        NSString *newString = [NSString stringWithFormat:@"http://www.scxxhs.com/huzhu/%@",photoStr];
        NSURL *url = [NSURL URLWithString:newString];
        [imageview sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"愿望-图"]];
        [scrollview addSubview:imageview];
    }
}
-(void)addSubviews{
    DetailHeaderView *headerView = [DetailHeaderView loadHeaderView];
    headerView.scrollview.contentSize = CGSizeMake(kScreenWidth * self.model.photoArray.count, headerView.scrollview.frame.size.height);
    headerView.scrollview.pagingEnabled = YES;
    headerView.ownerVC = self;
    headerView.model = self.model;
    if (self.model.photoArray.count == 0) {
        UIImageView *imageview = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, headerView.scrollview.frame.size.height)];
        imageview.image = [UIImage imageNamed:@"愿望-图"];
        [headerView.scrollview addSubview:imageview];
    }else if(self.model.photoArray.count != 0){
      [self addImageView:headerView.scrollview];
    }
    headerView.titleLabel.text = self.model.title;
    headerView.priceLabel.text = [NSString stringWithFormat:@"%ld",(long)self.model.price];
    headerView.niceNameLabel.text = self.model.userNiceName;
    NSString *avatar = [NSString stringWithFormat:@"http://www.scxxhs.com/huzhu/%@",self.model.avatar];
    NSURL *url = [NSURL URLWithString:avatar];
    [headerView.headerImageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"icon-互助类"]];
    headerView.rewardNumLabel.text = [NSString stringWithFormat:@"已支持%ld",(long)self.model.wishRewardNum];
    headerView.rewardPriceLabel.text = [NSString stringWithFormat:@"已打赏：¥%.0f",self.model.wishRewardPrice];
    if (self.model.price == 0 && self.model.wishRewardPrice == 0) {
        headerView.progressPercentLabel.text = [NSString stringWithFormat:@"0%%"];
        headerView.progressView.progress = 0;
    }else if (self.model.price == 0 && self.model.wishRewardPrice != 0){
        headerView.progressPercentLabel.text = [NSString stringWithFormat:@"100%%"];
        headerView.progressView.progress = 1;
    }else{
        headerView.progressPercentLabel.text = [NSString stringWithFormat:@"%.0f%%",self.model.wishRewardPrice/self.model.price];
        headerView.progressView.progress = self.model.wishRewardPrice/self.model.price;
    }
    PLLOG(@"Endtime:%@",self.model.wishEndTime);
    headerView.residueDayLabel.text = [NSString stringWithFormat:@"剩余0天"];
    self.headerview = headerView;
    self.tableView.tableHeaderView = self.headerview;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    self.btn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.btn.frame = CGRectMake(0, 0, 20, 20);
    if (self.model.isFavorites) {
        [self.btn setImage:[UIImage imageNamed:@"愿望-收藏选中"] forState:UIControlStateNormal];
        [self.btn addTarget:self action:@selector(getCollect) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *collectBtn = [[UIBarButtonItem alloc]initWithCustomView:self.btn];
        self.navigationItem.rightBarButtonItem = collectBtn;
    }else{
        [self.btn setImage:[UIImage imageNamed:@"愿望-收藏"] forState:UIControlStateNormal];
        [self.btn addTarget:self action:@selector(getCollect) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *collectBtn = [[UIBarButtonItem alloc]initWithCustomView:self.btn];
        self.navigationItem.rightBarButtonItem = collectBtn;
    }

}
-(void)getCollect{
    PLLOG(@"as");
    UserModel *user = [UserModel sharedUserModel];
    if (user.islogin) {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSDictionary *dic = [defaults objectForKey:@"userInfo"];
        NSString *idStr = dic[@"id"];
        __weak typeof(self) myself = self;
        if (self.flag == 0) {
            NSDictionary *dic = @{@"wish_id":@(self.model.wishId),@"user_id":idStr};
            [self.btn setImage:[UIImage imageNamed:@"愿望-收藏选中"] forState:UIControlStateNormal];
            [ResponseManager startPostRequestWithURLString:kCollectWishURL parameters:dic completionHandler:^(FBResponse *response) {
                if (response.success) {
                    [myself addAlertControllerWithTitle:@"提示" message:@"收藏成功" actionNum:1 style:UIAlertControllerStyleAlert handler:nil];
                    myself.flag = 1;
                    PLLOG(@"%@",response.resultValue);
                }else{
                    [myself addAlertControllerWithTitle:@"提示" message:@"收藏失败" actionNum:2 style:UIAlertControllerStyleAlert handler:^(UIAlertAction *action) {
                        [myself getCollect];
                    }];
                    PLLOG(@"%@",response.resultDesc);
                }
            }];
        }else{
            NSDictionary *dic = @{@"wish_id":@(self.model.wishId),@"user_id":idStr};
            [self.btn setImage:[UIImage imageNamed:@"愿望-收藏"] forState:UIControlStateNormal];
            [ResponseManager startPostRequestWithURLString:kRemoveCollectWishURL parameters:dic completionHandler:^(FBResponse *response) {
                if (response.success) {
                    [myself addAlertControllerWithTitle:@"提示" message:@"取消收藏" actionNum:1 style:UIAlertControllerStyleAlert handler:nil];
                    myself.flag = 0;
                    PLLOG(@"%@",response.resultValue);
                }else{
                    [myself addAlertControllerWithTitle:@"提示" message:@"取消失败" actionNum:2 style:UIAlertControllerStyleAlert handler:^(UIAlertAction *action) {
                        [myself getCollect];
                    }];
                    PLLOG(@"%@",response.resultDesc);
                }
            }];
            
        }

    }else{
        MemberViewController *vc = [[MemberViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }
    
    
}
-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    self.headerview.frame = CGRectMake(0, 0, kScreenWidth, 300 * kScreenHeightScale);
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self.tabBarController.tabBar setHidden:YES];
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [self.tabBarController.tabBar setHidden:NO];
}
-(void)getRequest{
    __weak typeof(self) myself = self;
    NSDictionary *parameter = @{@"post_id":@(self.model.wishId)};
    [ResponseManager startGetRequestWithURLString:kGetCommentURL parameters:parameter completionHandler:^(FBResponse *response) {
        if (response.success) {
            PLLOG(@"%@",response.resultValue);
            myself.dataSource = [response.resultValue copy];
            [myself.tableView reloadData];
        }else{
            PLLOG(@"%@",response.resultDesc);
        }
    }];
}
-(void)commentRequest{
    __weak typeof(self) myself = self;
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *dic = [defaults objectForKey:@"userInfo"];
    NSString *idStr = dic[@"id"];
    NSDictionary *parameter = @{@"post_id":@(self.model.wishId),@"content":self.commentView.textView.text,@"to_uid":@(self.model.userId),@"user_id":idStr};
    [ResponseManager startGetRequestWithURLString:kCommentPulish parameters:parameter completionHandler:^(FBResponse *response) {
        if (response.success) {
            [myself addAlertControllerWithTitle:@"提示" message:response.resultDesc actionNum:1 style:UIAlertControllerStyleAlert handler:^(UIAlertAction *action) {
                [myself getRequest];
                [myself.commentView removeFromSuperview];
            }];
            PLLOG(@"%@",response.resultValue);
        }else{
            [myself addAlertControllerWithTitle:@"提示" message:response.resultDesc actionNum:2 style:UIAlertControllerStyleAlert handler:^(UIAlertAction *action) {
                [myself commentRequest];
            }];
            PLLOG(@"%@",response.resultDesc);
        }
    }];

}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0 && !self.btnBool) {
        return 1;
    }else if(section == 0  && self.btnBool){
        return 0;
    }
    else{
        return self.dataSource.count;
    }
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        DetailAnotherTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DetailAnotherTableViewCell" forIndexPath:indexPath];
        cell.label.text = self.model.wishDesc;
        return cell;
    }else{
        DetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DetailTableViewCell" forIndexPath:indexPath];
        NSString *str = self.dataSource[indexPath.row][@"avatar"];
        NSString *newStr = [NSString stringWithFormat:@"http://www.scxxhs.com/huzhu/%@",str];
        NSURL *url = [NSURL URLWithString:newStr];
        [cell.image sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"icon-互助类"]];
        cell.detailLabel.text = self.dataSource[indexPath.row][@"content"];
        NSLog(@"%@",cell.detailLabel.text);
        cell.timeLabel.text = self.dataSource[indexPath.row][@"createtime"];
        self.cellHeight = [cell heightForText:cell.detailLabel.text];
        cell.idStr = self.dataSource[indexPath.row][@"uid"];
        cell.model = self.dataSource[indexPath.row][@"mobile"];
        if ([self.dataSource[indexPath.row][@"user_nicename"] isKindOfClass:[NSNull class]]) {
            cell.niceName = @"NULL";
        }else{
            cell.niceName = self.dataSource[indexPath.row][@"user_nicename"];
        }
        cell.ownerVC = self;
        return cell;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0 && !self.btnBool) {
        CGRect rect = [self.model.wishDesc boundingRectWithSize:CGSizeMake(kScreenWidth, 200 * kScreenHeightScale) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]} context:nil];
        return rect.size.height + 10;
    }else if (indexPath.section == 0 && self.btnBool){
        return 0;
    }
    else{
        return kScreenHeightScale * ceil(self.cellHeight.size.height) + 50;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 40 * kScreenHeightScale;
    }else{
        return 40 * kScreenHeightScale;
    }
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        DetailHeaderAnotherView *view = [DetailHeaderAnotherView loadheaderView];
        view.delegate = self;
        view.label1.text = [NSString stringWithFormat:@"详情：%@",self.model.title];
        self.anotherHeaderView = view;
        return view;
    }else{
        UINib *nib = [UINib nibWithNibName:@"DetailCellHeaderView" bundle:nil];
        UIView *view = [[nib instantiateWithOwner:nil options:nil]firstObject];
        return view;
    }
}
-(NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}
- (IBAction)shareBtnTaped:(id)sender {
    UserModel *user = [UserModel sharedUserModel];
    if (user.islogin) {
        
        
        
    }else{
        MemberViewController *vc = [[MemberViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}
- (IBAction)commentBtnTaped:(id)sender {
    UserModel *user = [UserModel sharedUserModel];
    if (user.islogin) {
        CommentView *view = [CommentView loadView];
        view.delegate = self;
        view.textView.delegate = self;
        view.textView.returnKeyType = UIReturnKeyDone;
        view.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
        self.commentView = view;
        [self.view addSubview:view];

    }else{
        MemberViewController *vc = [[MemberViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    UITouch *touch = touches.anyObject;
    CGPoint point = [touch locationInView:self.commentView.hudView];
    if ([self.commentView.hudView.layer containsPoint:point]) {
        [self.commentView removeFromSuperview];
    }
}
- (IBAction)payBtnTaped:(id)sender {
    UserModel *user = [UserModel sharedUserModel];
    if (user.islogin) {
        PayViewController *vc = [[PayViewController alloc]init];
        vc.wishID = [NSString stringWithFormat:@"%ld",self.model.wishId];
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        MemberViewController *vc = [[MemberViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}
#pragma mark --Delegate
-(void)btnTaped:(UIButton *)btn{
    self.btnBool = !self.btnBool;
    PLLOG(@"btnBool:%d",self.btnBool);
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];
}

-(void)textViewDidChange:(UITextView *)textView{
    if (textView) {
        PLLOG(@"textView changed");
        CGRect rect = [textView.text boundingRectWithSize:CGSizeMake(CGRectGetWidth(textView.frame), 200 * kScreenHeightScale) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]} context:nil];
        CGFloat height = rect.size.height > 80? rect.size.height+10 : 80;
        CGRect textViewFrame = textView.frame;
        textViewFrame.size.height = height;
        self.commentView.textView.frame = textViewFrame;
        CGRect viewFrame = self.commentView.view.frame;
        viewFrame.size.height = height + 20;
        self.commentView.view.frame = viewFrame;
        
    }
}
-(void)sendBtnTaped:(UIButton *)btn{
    [self commentRequest];
}


@end
